<template>
  <div class="log-viewer">
    <div class="log-header">
      <h3>执行日志</h3>
      <div class="log-controls">
        <!-- 日志级别过滤 -->
        <div class="level-filter">
          <button 
            v-for="level in logLevels" 
            :key="level.value"
            :class="['level-btn', `level-${level.value}`, { active: selectedLevels.includes(level.value) }]"
            @click="toggleLevel(level.value)"
          >
            {{ level.label }}
          </button>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn btn-clear" @click="clearLogs" :disabled="logs.length === 0">
            <i class="fas fa-trash"></i> 清空
          </button>
          <button class="btn btn-download" @click="downloadLogs" :disabled="logs.length === 0">
            <i class="fas fa-download"></i> 导出
          </button>
          <button 
            class="btn btn-scroll" 
            @click="autoScroll = !autoScroll"
            :class="{ active: autoScroll }"
          >
            <i class="fas fa-arrow-down"></i> 自动滚动
          </button>
        </div>
      </div>
    </div>
    
    <div class="log-content" ref="logContent">
      <div class="log-empty" v-if="filteredLogs.length === 0">
        <p v-if="logs.length === 0">暂无日志记录</p>
        <p v-else>当前筛选条件下无日志记录</p>
      </div>
      
      <div 
        v-for="log in filteredLogs" 
        :key="log.id"
        :class="['log-entry', `log-${log.level}`]"
      >
        <div class="log-time">{{ log.displayTime }}</div>
        <div class="log-level">
          <span :class="`level-badge level-${log.level}`">{{ log.level.toUpperCase() }}</span>
        </div>
        <div class="log-message">{{ log.message }}</div>
        <div class="log-data" v-if="log.data && showData">
          <pre>{{ formatLogData(log.data) }}</pre>
        </div>
      </div>
    </div>
    
    <div class="log-footer" v-if="logs.length > 0">
      <small>共 {{ logs.length }} 条日志，显示 {{ filteredLogs.length }} 条</small>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LogViewer',
  props: {
    logs: {
      type: Array,
      default: () => []
    },
    showData: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      selectedLevels: ['info', 'success', 'warning', 'error'],
      autoScroll: true,
      logLevels: [
        { value: 'info', label: '信息' },
        { value: 'success', label: '成功' },
        { value: 'warning', label: '警告' },
        { value: 'error', label: '错误' }
      ]
    }
  },
  computed: {
    filteredLogs() {
      return this.logs.filter(log => this.selectedLevels.includes(log.level))
    }
  },
  watch: {
    filteredLogs: {
      handler() {
        if (this.autoScroll) {
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        }
      },
      flush: 'post'
    }
  },
  methods: {
    toggleLevel(level) {
      const index = this.selectedLevels.indexOf(level)
      if (index > -1) {
        this.selectedLevels.splice(index, 1)
      } else {
        this.selectedLevels.push(level)
      }
    },
    clearLogs() {
      this.$emit('clear-logs')
    },
    downloadLogs() {
      const logText = this.filteredLogs.map(log => {
        return `[${log.timestamp}] [${log.level.toUpperCase()}] ${log.message}${log.data ? '\n' + JSON.stringify(log.data, null, 2) : ''}`
      }).join('\n\n')
      
      const blob = new Blob([logText], { type: 'text/plain;charset=utf-8' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `image-update-logs-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.txt`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    },
    scrollToBottom() {
      const content = this.$refs.logContent
      if (content) {
        content.scrollTop = content.scrollHeight
      }
    },
    formatLogData(data) {
      try {
        return JSON.stringify(data, null, 2)
      } catch (e) {
        return String(data)
      }
    }
  },
  mounted() {
    // 初始滚动到底部
    this.scrollToBottom()
  }
}
</script>

<style scoped>
.log-viewer {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
  display: flex;
  flex-direction: column;
  height: 400px;
}

.log-header {
  padding: 16px;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 8px 8px 0 0;
}

.log-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #374151;
}

.log-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.level-filter {
  display: flex;
  gap: 4px;
}

.level-btn {
  padding: 4px 8px;
  border: 1px solid transparent;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  opacity: 0.6;
}

.level-btn.active {
  opacity: 1;
}

.level-info {
  background: #dbeafe;
  color: #1e40af;
  border-color: #3b82f6;
}

.level-success {
  background: #dcfce7;
  color: #166534;
  border-color: #10b981;
}

.level-warning {
  background: #fef3c7;
  color: #92400e;
  border-color: #f59e0b;
}

.level-error {
  background: #fee2e2;
  color: #dc2626;
  border-color: #ef4444;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 12px;
  color: #374151;
  transition: all 0.2s ease;
}

.btn:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.log-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  background: #fafafa;
}

.log-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #9ca3af;
}

.log-entry {
  display: grid;
  grid-template-columns: 80px 60px 1fr;
  gap: 8px;
  padding: 6px 8px;
  margin-bottom: 2px;
  border-radius: 4px;
  font-size: 12px;
  align-items: start;
}

.log-entry:hover {
  background: rgba(0, 0, 0, 0.03);
}

.log-info {
  background: rgba(59, 130, 246, 0.05);
}

.log-success {
  background: rgba(16, 185, 129, 0.05);
}

.log-warning {
  background: rgba(245, 158, 11, 0.05);
}

.log-error {
  background: rgba(239, 68, 68, 0.05);
}

.log-time {
  color: #6b7280;
  font-family: monospace;
}

.level-badge {
  padding: 2px 6px;
  border-radius: 3px;
  font-weight: 500;
  font-size: 10px;
  text-align: center;
}

.level-badge.level-info {
  background: #3b82f6;
  color: white;
}

.level-badge.level-success {
  background: #10b981;
  color: white;
}

.level-badge.level-warning {
  background: #f59e0b;
  color: white;
}

.level-badge.level-error {
  background: #ef4444;
  color: white;
}

.log-message {
  color: #374151;
  line-height: 1.4;
  word-break: break-word;
}

.log-data {
  grid-column: 1 / -1;
  margin-top: 4px;
}

.log-data pre {
  background: rgba(0, 0, 0, 0.05);
  padding: 8px;
  border-radius: 4px;
  font-size: 11px;
  overflow-x: auto;
  margin: 0;
  color: #4b5563;
}

.log-footer {
  padding: 8px 16px;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  text-align: right;
  color: #6b7280;
  border-radius: 0 0 8px 8px;
}

/* 滚动条样式 */
.log-content::-webkit-scrollbar {
  width: 6px;
}

.log-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.log-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.log-content::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}
</style>